package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.ResultData;
import com.yh.correct.model.SysLog;
import com.yh.correct.service.ISysLogService;

/**
 * 系统日志控制层
 * @author Administrator
 *
 */
@RestController
@RequestMapping(value="/syslog")
public class SysLogController {
	/**
	 * 日志
	 */
	private static Logger logger = LogManager.getLogger(SysLogController.class);
	/**
	 * 系统日志service层接口
	 */
	@Autowired
	private ISysLogService logService;
	
	/**
	 * 跳转到日志管理页面
	 * @return
	 */
	@RequestMapping(value = "/show")
	public ModelAndView toShow() {
		ModelAndView mv = new ModelAndView("/system/syslog");
		return mv;
	}
	
	/**
	 * 获取日志，显示图表,最新的100条
	 * @return
	 */
	@RequestMapping(value="/echarts")
	public ResultData getData(Integer pageNum,Integer pageSize){
		Map<String,Object> condition=new HashMap<String,Object>();
		condition.put("pageNum", pageNum);
		condition.put("pageSize", pageSize);
		List<Object> list=null;
		try {
			list=logService.findListByCondition(condition).getList();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultData rd = new ResultData();
		if (list!=null) {
			String[] xAxisArr=new String[list.size()];
			String[] series=new String[list.size()];
			for(int i=0;i<list.size();i++){
				xAxisArr[i]=((Map<String, Object>) list.get(list.size()-1-i)).get("createtime").toString();
				series[i]=(String) ((Map<String, Object>) list.get(list.size()-1-i)).get("time");
			}
			List data=new ArrayList();
			data.add(xAxisArr);
			data.add(series);
			rd.setCode(0);
			rd.setMessage("获取成功！");
			rd.setData(data);
			return rd;
		} else {
			rd.setCode(4001);
			rd.setMessage("获取失败！");
			return rd;
		}
	}
	
	/**
	 * 动态模糊查询日志信息
	 * @param username
	 * @param ip
	 * @param starttime
	 * @param endtime
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/search")
	public ResultData searchLog(String username,String ip,String starttime,String endtime,Integer pageNum,Integer pageSize){
		Map<String,Object> condition=new HashMap<String,Object>();
		condition.put("username", username);
		condition.put("ip", ip);
		condition.put("starttime", starttime);
		condition.put("endtime", endtime);
		condition.put("pageNum", pageNum);
		condition.put("pageSize", pageSize);
		PageInfo<Object> pageInfo=null;
		try {
			pageInfo=logService.findListByCondition(condition);
		} catch (Exception e) {
			// TODO: handle exception
		}
		ResultData rd = new ResultData();
		if(pageInfo!=null){
			List<Object> list=new ArrayList<Object>();
			list.add(pageInfo);
			rd.setCode(0);
			rd.setMessage("获取成功！");
			rd.setData(list);
			return rd;
		}else {
			rd.setCode(4001);
			rd.setMessage("获取失败！");
			return rd;
		}
	}
	/**
	 * 删除日志
	 * @param log
	 * @return
	 */
	@RequestMapping(value="/doDel")
	public ResultData doDelLog(SysLog log){
		int i=0;
		try {
			i=logService.deleteSysLog(log);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("删除成功！");
		}else{
			rd.setCode(4001);
			rd.setMessage("删除失败！");
		}
		return rd;
	}
	
	/**
	 * 导出excel
	 * @return
	 */
	@RequestMapping("/excel")
	public ResultData exportExcel(HttpServletRequest reqeust,HttpServletResponse response) throws Exception{
		 String fileName="系统日志";
	        //填充projects数据
		 	List<Map<String,Object>> list = logService.findListAll();
	        LinkedList<Map<String, Object>> projects= new LinkedList(list);
	        Map<String,Object> map=new HashMap<String,Object>();
	        map.put("sheetName", "sheet1");
	        projects.addFirst(map);
	        String columnNames[]={"序号","用户名称","客户端IP","客户端MAC","访问URL","访问方式","执行类名","执行方法","运行耗时","日志时间"};//列名
	        String keys[]={"id","usename","ip","mac","url","type","classname","method","time","createtime"};//map中的key
	        ByteArrayOutputStream os = new ByteArrayOutputStream();
	        try {
	            ExcelUtil.createWorkBook(projects,keys,columnNames).write(os);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        byte[] content = os.toByteArray();
	        InputStream is = new ByteArrayInputStream(content);
	        // 设置response参数，可以打开下载页面
	        response.reset();
	        response.setContentType("application/vnd.ms-excel;charset=utf-8");
	        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
	        ServletOutputStream out = response.getOutputStream();
	        BufferedInputStream bis = null;
	        BufferedOutputStream bos = null;
	        try {
	            bis = new BufferedInputStream(is);
	            bos = new BufferedOutputStream(out);
	            byte[] buff = new byte[2048];
	            int bytesRead;
	            // Simple read/write loop.
	            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
	                bos.write(buff, 0, bytesRead);
	            }
	        } catch (final IOException e) {
	            throw e;
	        } finally {
	            if (bis != null)
	                bis.close();
	            if (bos != null)
	                bos.close();
	        }
//	        ResultData rd=new ResultData();
//	        rd.setMessage("导出成功！");
//	        return rd;
	        return null;
	}
}
